package com.putao.tinytime.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.putao.tinytime.constants.PuTaoConstants;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.res.AssetManager;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;


public class CommonUtils {

    public static File getOutputMediaFile() {
        File mediaStorageDir = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),

                PuTaoConstants.PAIAPI_PHOTOS_FOLDER);
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("PAIAPI_PHOTOS_FOLDER", "failed to create directory");
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + "_" + (int) (Math.random() * 10) + (int) (Math.random() * 10) + ".jpg");

        return mediaFile;
    }

    public static String getDateTime(String formatStr) {
        if (TextUtils.isEmpty(formatStr)) {
            formatStr = "yyyy-mm-dd HH:mm:ss";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatStr);
        return simpleDateFormat.format(new Date());
    }

    public static Dialog dialog(Context context, String message, String b1text,
                                String b2text, OnClickListener... listeners) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(message);
        return builder.show();
    }

    /**
     * base64加密
     *
     * @param encodeStr
     * @return
     */
    public static String encode(String encodeStr) {
        return new String(Base64.encode(encodeStr.getBytes(), Base64.DEFAULT));
    }

    /**
     * base64解密
     *
     * @param encodeStr
     * @return
     */
    public static String decode(String encodeStr) {
        return new String(Base64.decode(encodeStr.getBytes(), Base64.DEFAULT));
    }

    public static final String GENDER_NONE = "0";
    public static final String GENDER_MALE = "1";
    public static final String GENDER_FEMALE = "2";

    /**
     * 性别标记解析
     *
     * @param purposeFlag
     * @return
     */
    public static String parseGender(String genderFlag) {
        if (null != genderFlag) {
            genderFlag = genderFlag.trim();
            if (GENDER_NONE.equals(genderFlag)) {
                genderFlag = "不限";
            } else if (GENDER_MALE.equals(genderFlag)) {
                genderFlag = "男";
            } else if (GENDER_FEMALE.equals(genderFlag)) {
                genderFlag = "女";
            }
        }
        return genderFlag;
    }

    public static String parseTime(Object time) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        if (time instanceof Long) {
            date = new Date((Long) time);
        } else if (time instanceof String) {
            try {
                date = fmt.parse(String.valueOf(time));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return fmt.format(date);
    }

    public static String parseTime(Object time, String type) {
        DateFormat fmt = new SimpleDateFormat(type);
        Date date = null;
        if (time instanceof Long) {
            date = new Date((Long) time);
        } else if (time instanceof String) {
            try {
                date = fmt.parse(String.valueOf(time));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return fmt.format(date);
    }

    public static String parseTimeNew(Object time) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        if (time instanceof Long) {
            date = new Date((Long) time);
        } else if (time instanceof String) {
            try {
                date = fmt.parse(String.valueOf(time));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return fmt.format(date);
    }

    public static String parseDate(Date date) {
        DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return fmt.format(date);
    }

    // public static String getFormatDate(Object time)
    // {
    // String resultTime = "";
    // Date date = null;
    // long needTime = 0;
    // if (time instanceof String)
    // {
    // DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // try
    // {
    // date = fmt.parse(String.valueOf(time));
    // needTime = date.getTime();
    // B5MLog.e(time + " " + needTime);
    // }
    // catch (ParseException e)
    // {
    // // TODO Auto-generated catch block
    // B5MLog.w(e.toString());
    // needTime = B5MStringHelper.stringToLong((String) time);
    // }
    // }
    // else if (time instanceof Long)
    // {
    // needTime = (Long) time;
    // }
    // resultTime = B5MTimeHelper.getListTime(needTime);
    // return resultTime;
    // }

    public static boolean isInDay(Context context, long time, int day) {
        if ((System.currentTimeMillis() - day * 24 * 60 * 60 * 1000) < time) {
            return true;
        } else {
            return false;
        }
    }

    public static String getDouble(String d) {
        DecimalFormat decimalFormat = new DecimalFormat("#.0");
        return decimalFormat.format(d);
    }

    public static long dataStr2Long(String dateStr) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(dateStr);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return date.getTime();
    }

    public static Properties getConfig(Context context) {
        Properties props = new Properties();
        AssetManager asset = context.getAssets();
        InputStream input = null;
        try {
            input = asset.open("config.properties");
            props.load(input);
        } catch (IOException e) {
            Log.e("工具包异常", "获取配置文件异常");
            e.printStackTrace();
        }
        return props;
    }

    public static String packUrl(HashMap<String, Object> params) {
        if (params == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        String value = "";
        boolean bFirst = true;
        for (String key : params.keySet()) {
            value = (String) params.get(key);
            if ((!TextUtils.isEmpty(key)) && (!TextUtils.isEmpty(value))) {
                try {
                    if (bFirst)
                        bFirst = false;
                    else {
                        sb.append("&");
                    }
                    sb.append(URLEncoder.encode(key, "UTF-8")).append("=")
                            .append(URLEncoder.encode(value, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }

    public static long calcTokenExpiresInDays(long ExpiresTime) {
        long days = TimeUnit.MILLISECONDS.toDays(ExpiresTime
                - System.currentTimeMillis());
        return days;
    }

    public static String getCurrentDateTimeString() {
        Calendar cal = Calendar.getInstance();
        String dateTime;
        dateTime = "Memo-" + cal.get(Calendar.DAY_OF_MONTH) + "-"
                + cal.get(Calendar.MONTH) + "-" + cal.get(Calendar.YEAR) + "-"
                + cal.get(Calendar.HOUR) + "-" + cal.get(Calendar.MINUTE) + "-"
                + cal.get(Calendar.SECOND);
        return dateTime;
    }

    /**
     * URL转换为链接
     *
     * @param urlText
     * @return String
     * @author Boyer
     */
    public static String urlToLink(String urlText) {
        // 匹配的条件选项为结束为空格(半角和全角)、换行符、字符串的结尾或者遇到其他格式的文本
        String regexp = "(((http|ftp|https|file)://)|((?<!((http|ftp|https|file)://))www\\.))" // 以http...或www开头
                + ".*?" // 中间为任意内容，惰性匹配
                + "(?=(&nbsp;|\\s|　|<br />|$|[<>]))"; // 结束条件
        Pattern pattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(urlText);
        StringBuffer stringbuffer = new StringBuffer();
        while (matcher.find()) {
            String url = matcher.group().substring(0, 3).equals("www") ? "http://"
                    + matcher.group()
                    : matcher.group();
            String tempString = "<a href=\"" + url + "\">" + matcher.group()
                    + "</a>";
            // 这里对tempString中的"\"和"$"进行一次转义，因为下面对它替换的过程中appendReplacement将"\"和"$"作为特殊字符处理
            int tempLength = tempString.length();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < tempLength; ++i) {
                char c = tempString.charAt(i);
                if (c == '\\' || c == '$') {
                    buffer.append("\\").append(c);
                } else {
                    buffer.append(c);
                }
            }
            tempString = buffer.toString();
            matcher.appendReplacement(stringbuffer, tempString);
        }
        matcher.appendTail(stringbuffer);
        return stringbuffer.toString();
    }

    /**
     * 文本中含有URL的内容，画面表示为链接
     *
     * @param note
     * @return
     * @author Boyer
     */
    public static String textToLinks(String note) {
        // 转换的思想为把文本中不是链接("/a>"和"<a "之间)的内容逐个进行转换
        // 把字符串中的"\"和"$"加上转义符，避免appendReplacement替换字符串的时候将它们作为特殊字符处理
        int noteLength = note.length();
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < noteLength; ++i) {
            char c = note.charAt(i);
            if (c == '\\' || c == '$') {
                buffer.append("\\").append(c);
            } else {
                buffer.append(c);
            }
        }
        String linkNote = "/a>" + buffer.toString() + "<a ";
        String regexp = "(?<=/a>).*?(?=<a )";
        Pattern pattern = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(linkNote);
        StringBuffer stringbuffer = new StringBuffer();
        while (matcher.find()) {
            String tempString = urlToLink(matcher.group());
            matcher.appendReplacement(stringbuffer, tempString);
        }
        matcher.appendTail(stringbuffer);
        String result = stringbuffer.toString();
        // 返回的结果去掉加入的"/a>" 和"<a "
        return result.substring(3, result.length() - 3);
    }
    //
    // /**
    // * 获取订单商品的支付来源
    // * @return
    // */
    // public static String getOrderToFrom()
    // {
    // return B5MPreferenceHelper.readStringValue(MainApplication.getInstance(),
    // Constants.PREFERENCE_EVENT_AGENT, "帮5买APP");
    // }
    //
    // /**
    // * 设置订单商品的支付来源
    // */
    // public static void setOrderToFrom(String value)
    // {
    // B5MPreferenceHelper.saveStringValue(MainApplication.getInstance(),
    // Constants.PREFERENCE_EVENT_AGENT, value);
    // }


    /**
     * 用来判断服务是否运行.
     *
     * @param context
     * @param className 判断的服务名字
     * @return true 在运行 false 不在运行
     */
//    public static boolean isServiceRunning(Context mContext, String className) {
//        boolean isRunning = false;
//        ActivityManager activityManager = (ActivityManager)
//                mContext.getSystemService(Context.ACTIVITY_SERVICE);
//        List<ActivityManager.RunningServiceInfo> serviceList
//                = activityManager.getRunningServices(30);
//        if (!(serviceList.size() > 0)) {
//            return false;
//        }
//        for (int i = 0; i < serviceList.size(); i++) {
//            Loger.i("class name:" + serviceList.get(i).service.getClassName());
//            if (serviceList.get(i).service.getClassName().equals(className) == true) {
//                isRunning = true;
//                break;
//            }
//        }
//        return isRunning;
//    }
    public static boolean isServiceRunning(Context mContext, String className) {
        ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (className.equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}
